<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { useDocumentStore } from '@/stores/document';
import { useTemplateStore } from '@/stores/template';

const router = useRouter();
const userStore = useUserStore();
const documentStore = useDocumentStore();
const templateStore = useTemplateStore();

// 最近的文档
const recentDocuments = ref([]);
// 推荐的模板
const recommendedTemplates = ref([]);

// 加载状态
const loading = ref({
  documents: false,
  templates: false
});

// 计算属性：用户是否已登录
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 获取最近的文档
const fetchRecentDocuments = async () => {
  if (!isLoggedIn.value) return;
  
  loading.value.documents = true;
  try {
    // 确保用户已登录且初始化完成
    if (!userStore.currentUser || !userStore.currentUser.id) {
      console.log('用户未完全初始化，跳过获取文档');
      return;
    }
    
    await documentStore.fetchDocuments(1, 5);
    recentDocuments.value = documentStore.documents;
  } catch (error) {
    console.error('Failed to fetch recent documents:', error);
  } finally {
    loading.value.documents = false;
  }
};

// 获取推荐的模板
const fetchRecommendedTemplates = async () => {
  if (!isLoggedIn.value) return;
  
  loading.value.templates = true;
  try {
    await templateStore.fetchTemplates(1, 4);
    recommendedTemplates.value = templateStore.templates;
  } catch (error) {
    console.error('Failed to fetch recommended templates:', error);
  } finally {
    loading.value.templates = false;
  }
};

// 创建新文档
const createNewDocument = () => {
  router.push('/documents/create');
};

// 使用模板创建文档
const createFromTemplate = (templateId) => {
  router.push(`/documents/create?templateId=${templateId}`);
};

// 查看文档详情
const viewDocument = (documentId) => {
  router.push(`/documents/${documentId}`);
};

// 组件挂载时获取数据
onMounted(async () => {
  try {
    // 确保用户信息已初始化
    if (userStore.token && (!userStore.currentUser || !userStore.currentUser.id)) {
      try {
        await userStore.initUser();
        console.log('User initialized:', userStore.currentUser);
      } catch (initError) {
        console.error('Failed to initialize user:', initError);
        // 如果初始化失败，不要继续尝试获取文档
        return;
      }
    }
    
    // 只有当用户完全初始化后才获取文档和模板
    if (userStore.token && userStore.currentUser && userStore.currentUser.id) {
      console.log('User is logged in and initialized, fetching documents and templates');
      try {
        await Promise.all([
          fetchRecentDocuments(),
          fetchRecommendedTemplates()
        ]);
      } catch (fetchError) {
        console.error('Error fetching documents or templates:', fetchError);
      }
    } else {
      console.log('User is not logged in or not initialized, showing welcome page');
    }
  } catch (error) {
    console.error('Error in HomeView onMounted:', error);
  }
});
</script>

<template>
  <div class="home-container">
    <!-- 未登录状态显示欢迎信息 -->
    <div v-if="!userStore.token && !isLoggedIn" class="welcome-section">
      <div class="welcome-content">
        <h1 class="welcome-title">欢迎使用在线文档协作平台</h1>
        <p class="welcome-description">
          我们的平台提供强大的文档编辑和实时协作功能，帮助您和团队更高效地工作。
        </p>
        <div class="welcome-actions">
          <router-link to="/login" class="btn-primary">登录</router-link>
          <router-link to="/register" class="btn-secondary">注册</router-link>
        </div>
      </div>
      <div class="welcome-image">
        <img src="@/assets/collaboration.svg" alt="协作插图" />
      </div>
    </div>

    <!-- 已登录状态显示文档和模板 -->
    <div v-if="userStore.token || isLoggedIn" class="dashboard">
      <div class="dashboard-header">
        <h1 class="dashboard-title">欢迎回来，{{ userStore.currentUser?.userName }}</h1>
        <button @click="createNewDocument" class="create-doc-btn">
          <span class="icon">+</span> 新建文档
        </button>
      </div>

      <!-- 最近的文档 -->
      <section class="recent-documents-section">
        <div class="section-header">
          <h2 class="section-title">最近的文档</h2>
          <router-link to="/documents" class="view-all-link">查看全部</router-link>
        </div>

        <div v-if="loading.documents" class="loading-placeholder">
          <p>加载中...</p>
        </div>

        <div v-else-if="recentDocuments.length === 0" class="empty-state">
          <p>您还没有创建任何文档</p>
          <button @click="createNewDocument" class="btn-primary">创建第一个文档</button>
        </div>

        <div v-else class="documents-grid">
          <div 
            v-for="doc in recentDocuments" 
            :key="doc.id" 
            class="document-card"
            @click="viewDocument(doc.id)"
          >
            <div class="document-card-content">
              <h3 class="document-title">{{ doc.title }}</h3>
              <p class="document-meta">
                <span class="document-date">最后编辑: {{ new Date(doc.updateTime).toLocaleDateString() }}</span>
              </p>
            </div>
          </div>
        </div>
      </section>

      <!-- 推荐的模板 -->
      <section class="templates-section">
        <div class="section-header">
          <h2 class="section-title">推荐的模板</h2>
          <router-link to="/templates" class="view-all-link">查看全部</router-link>
        </div>

        <div v-if="loading.templates" class="loading-placeholder">
          <p>加载中...</p>
        </div>

        <div v-else-if="recommendedTemplates.length === 0" class="empty-state">
          <p>暂无推荐模板</p>
        </div>

        <div v-else class="templates-grid">
          <div 
            v-for="template in recommendedTemplates" 
            :key="template.id" 
            class="template-card"
            @click="createFromTemplate(template.id)"
          >
            <div class="template-card-content">
              <h3 class="template-title">{{ template.name }}</h3>
              <p class="template-category">{{ template.category }}</p>
            </div>
            <div class="template-card-footer">
              <div class="template-card-actions">
                <button class="use-template-btn" @click.stop="createDocFromTemplate(template.id)">使用此模板</button>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>
  </div>
</template>

<style scoped>
.home-container {
  width: 100%;
  height: calc(100vh - 120px); /* 减去header和footer的高度 */
  margin: 0;
  padding: 2rem;
  overflow-y: auto;
  background-color: #f9fafb;
  color: #374151;
}

/* 欢迎区域样式 */
.welcome-section {
  display: flex;
  align-items: center;
  gap: 4rem;
  margin-top: 2rem;
  background-color: white;
  border-radius: 16px;
  padding: 3rem;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.welcome-section:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.08);
}

.welcome-content {
  flex: 1;
}

.welcome-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: #111827;
  margin-bottom: 1rem;
  line-height: 1.2;
  background: linear-gradient(to right, #4f46e5, #7c3aed);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.welcome-description {
  font-size: 1.25rem;
  color: #6b7280;
  margin-bottom: 2rem;
  line-height: 1.6;
  max-width: 90%;
}

.welcome-actions {
  display: flex;
  gap: 1.25rem;
  margin-top: 0.5rem;
}

.welcome-image {
  flex: 1;
  display: flex;
  justify-content: center;
}

.welcome-image img {
  max-width: 100%;
  height: auto;
  filter: drop-shadow(0 10px 15px rgba(79, 70, 229, 0.2));
  transition: transform 0.5s ease;
}

.welcome-image img:hover {
  transform: scale(1.05) rotate(2deg);
}

/* 仪表盘样式 */
.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2.5rem;
  padding-bottom: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
}

.dashboard-title {
  font-size: 2rem;
  font-weight: 700;
  color: #111827;
  position: relative;
  padding-left: 0.5rem;
}

.dashboard-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0.25rem;
  bottom: 0.25rem;
  width: 4px;
  background: linear-gradient(to bottom, #4f46e5, #7c3aed);
  border-radius: 4px;
}

.create-doc-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.75rem;
  background-color: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.create-doc-btn:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.create-doc-btn .icon {
  font-size: 1.25rem;
  font-weight: 600;
}

/* 区域通用样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
  position: relative;
}

.section-title {
  margin-top: 8px;
  font-size: 1.375rem;
  font-weight: 600;
  color: #111827;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.section-title::before {
  content: '';
  display: inline-block;
  width: 12px;
  height: 12px;
  background-color: #4f46e5;
  border-radius: 50%;
}

.view-all-link {
  color: #4f46e5;
  text-decoration: none;
  font-weight: 500;
  font-size: 0.875rem;
  padding: 0.5rem 0.75rem;
  border-radius: 6px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
}

.view-all-link::after {
  content: '→';
  margin-left: 0.25rem;
  transition: transform 0.2s ease;
}

.view-all-link:hover {
  background-color: rgba(79, 70, 229, 0.1);
}

.view-all-link:hover::after {
  transform: translateX(3px);
}

/* 文档卡片样式 */
.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.document-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 140px;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

.document-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border-color: rgba(79, 70, 229, 0.2);
}

.document-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(to right, #4f46e5, #7c3aed);
  transform: scaleX(0);
  transform-origin: left;
  transition: transform 0.3s ease;
}

.document-card:hover::after {
  transform: scaleX(1);
}

.document-card-content {
  padding: 1.5rem;
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  z-index: 1;
}

.document-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 0.75rem;
  /* 文本溢出省略 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: color 0.2s ease;
}

.document-card:hover .document-title {
  color: #4f46e5;
}

.document-meta {
  margin-top: auto;
  font-size: 0.75rem;
  color: #6b7280;
  display: flex;
  align-items: center;
}

.document-date {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.document-date::before {
  content: '🕒';
  font-size: 0.875rem;
}

/* 模板卡片样式 */
.templates-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1.5rem;
}

.template-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
  cursor: pointer;
  height: 170px;
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
}

.template-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  border-color: rgba(79, 70, 229, 0.2);
}

.template-card::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: linear-gradient(to right, #7c3aed, #4f46e5);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
}

.template-card:hover::after {
  transform: scaleX(1);
}

.template-card-content {
  padding: 1.5rem 1.5rem 0rem 1.5rem;
  flex: 1;
  position: relative;
  z-index: 1;
}

.template-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #111827;
  margin-bottom: 0.75rem;
  /* 文本溢出省略 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  transition: color 0.2s ease;
}

.template-card:hover .template-title {
  color: #7c3aed;
}

.template-category {
  font-size: 0.875rem;
  color: #6b7280;
  margin-bottom: 0.75rem;
  display: inline-block;
  padding: 0.25rem 0.5rem;
  background-color: #f3f4f6;
  border-radius: 4px;
  transition: all 0.2s ease;
}

.template-card:hover .template-category {
  background-color: #ede9fe;
  color: #7c3aed;
}

.template-card-footer {
  padding: 1rem 1.5rem;
  border-top: 1px solid #e5e7eb;
  background-color: #f9fafb;
  transition: background-color 0.3s ease;
}

.template-card:hover .template-card-footer {
  background-color: #f5f3ff;
}

.template-card-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 0.5rem;
}

.use-template-btn {
  flex: 1;
  padding: 0.625rem 0.75rem;
  background-color: transparent;
  border: 1px solid #7c3aed;
  color: #7c3aed;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.use-template-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #7c3aed;
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.use-template-btn:hover {
  color: white;
  border-color: #7c3aed;
}

.use-template-btn:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}

/* 加载和空状态样式 */
.loading-placeholder,
.empty-state {
  padding: 3rem 0;
  text-align: center;
  color: #6b7280;
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin: 1rem 0;
}

.empty-state p {
  margin-bottom: 1.25rem;
  font-size: 1.125rem;
  color: #4b5563;
}

/* 按钮样式 */
.btn-primary,
.btn-secondary {
  display: inline-block;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 500;
  text-decoration: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  z-index: 1;
}

.btn-primary {
  background-color: #4f46e5;
  color: white;
  border: 1px solid #4f46e5;
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.btn-primary::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.1);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.btn-primary:hover {
  background-color: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(79, 70, 229, 0.3);
}

.btn-primary:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}

.btn-secondary {
  background-color: white;
  color: #4f46e5;
  border: 1px solid #4f46e5;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.btn-secondary::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(79, 70, 229, 0.05);
  transform: scaleX(0);
  transform-origin: right;
  transition: transform 0.3s ease;
  z-index: -1;
}

.btn-secondary:hover {
  background-color: #f5f5ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.btn-secondary:hover::before {
  transform: scaleX(1);
  transform-origin: left;
}
</style>
